﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace urBook.Engine
{
    /// <summary>
    /// Class Group represents a group object in the Address Book
    /// </summary>
    public class Group : IComparable, ICloneable
    {
        /// <summary>
        /// Default constructor for Group Object
        /// </summary>
        public Group()
        {
            contacts = new List<ContactCard>();
            name = "group";
            imageUrl = "";
        }

        [XmlArray("Contacts")]
        [XmlArrayItem("Contact")]
        public List<ContactCard> contacts { get; set; }
        [XmlAttribute("name")]
        public string name { get; set; }
        [XmlAttribute("imageUrl")]
        public string imageUrl { get; set; }

        public void addToGroup(ContactCard c)
        {
            if (!c.groups.Contains(name))
                c.groups.Add(name);

            if (!contacts.Contains(c))
                contacts.Add(c);
        }

        public void applyPhoto()
        {
            Photo photo = new Photo();
            photo.ext = imageUrl.Split('.').Last();
            photo.url = imageUrl;
            photo.value = Type.URL;
            foreach(ContactCard c in contacts)
                c.photo = photo;
        }

        public int CompareTo(object obj)
        {
            Group g = (Group)obj;
            return this.name.ToLower().Trim().CompareTo(g.name.ToLower().Trim());
        }

        public object Clone()
        {
            Group clone = new Group
            {
                name = this.name,
                imageUrl = this.imageUrl
            };

            foreach (ContactCard c in contacts)
                clone.contacts.Add((ContactCard)c.Clone());

            return clone;
        }
    }
}
